package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.codec.Base64;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.AuditService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 饭勺
 * @description 文本&图片审核工具方法的实现类
 * @createDate 2025/9/24 19:53
 */
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private Credential credential;

    @Autowired
    private VodConstantProperties vodConstantProperties;

    /**
     * 文本内容审核  -同步审核
     *
     * @param content
     * @return  建议：Block：建议屏蔽，Review ：建议人工复审，Pass：建议通过
     */
    @Override
    public String auditText(String content) {
        try {
        //1.实例化要请求产品的client对象,clientProfile是可选的
        TmsClient client = new TmsClient(credential, vodConstantProperties.getRegion());
        //2.实例化一个请求对象,每个接口都会对应一个request对象
        TextModerationRequest req = new TextModerationRequest();
        //对审核内容进行Base64编码
        req.setContent(Base64.encode(content));
        //3.返回的resp是一个TextModerationResponse的实例，与请求对象对应
            TextModerationResponse resp = client.TextModeration(req);
        //4.解析文本审核结果
            if (resp != null){
                String suggestion = resp.getSuggestion();
                log.info("文本审核结果: {}" ,suggestion);
                return suggestion.toLowerCase();
            }
        } catch (TencentCloudSDKException e) {
            log.error("文本内容审核失败: {}",content);
            throw new RuntimeException(e);
        }

        return null;
    }


    /**
     * 图片内容审核
     *
     * @param file
     * @return 建议：Block：建议屏蔽，Review ：建议人工复审，Pass：建议通过
     */
    @Override
    public String auditImage(MultipartFile file) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            ImsClient client = new ImsClient(credential, vodConstantProperties.getRegion());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            ImageModerationRequest req = new ImageModerationRequest();
            //对图片进行Base64编码
            //图片由于没有存在腾讯OSS服务器，所以不能使用FileUrl
            req.setFileContent(Base64.encode(file.getInputStream()));
            //3.返回的resp是一个ImageModerationResponse的实例，与请求对象对应
            ImageModerationResponse resp = client.ImageModeration(req);
            //4.解析得到建议结果
            if (resp != null) {
                String suggestion = resp.getSuggestion();
                log.error("图片审核结果: {}",suggestion);
                return suggestion.toLowerCase();
            }
/*        } catch (Exception e) {
            log.error("图片内容,{}审核失败", file.getOriginalFilename());
        }*/
        } catch (IOException e) {
            log.error("图片审核失败：{}", e.getMessage());
            throw new RuntimeException(e);
        } catch (TencentCloudSDKException e) {
            log.error("图片审核失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return null;
    }


    /**
     * 启动审核任务，开始对音视频文件发起审核任务
     *
     * @param mediaFileId 文件唯一标识
     * @return 审核任务ID
     */
    @Override
    public String startReviewTask(String mediaFileId) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, vodConstantProperties.getRegion());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            ReviewAudioVideoRequest req = new ReviewAudioVideoRequest();
            req.setFileId(mediaFileId);
            //3.返回的resp是一个ReviewAudioVideoResponse的实例，与请求对象对应
            ReviewAudioVideoResponse resp = client.ReviewAudioVideo(req);
            //4.获取审核任务ID
            if (resp != null) {
                String taskId = resp.getTaskId();
                return taskId;
            }
        } catch (TencentCloudSDKException e) {
            log.error("发起音视频审核任务失败：{}", e);
            throw new RuntimeException(e);
        }
        return null;
    }



    /**
     * 根据审核任务ID获取审核结果
     *
     * @param taskId
     * @return 建议：block：建议屏蔽，review ：建议人工复审，pass：建议通过
     */
    @Override
    public String getReviewResult(String taskId) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, vodConstantProperties.getRegion());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeTaskDetailRequest req = new DescribeTaskDetailRequest();
            req.setTaskId(taskId);
            //3.返回的resp是一个DescribeTaskDetailResponse的实例，与请求对象对应
            DescribeTaskDetailResponse resp = client.DescribeTaskDetail(req);
            //4.解析审核任务状态，以及审核建议结果
            if (resp != null) {
                //4.1 判断审核任务类型是否为：ReviewAudioVideo：音视频审核任务；
                if("ReviewAudioVideo".equals(resp.getTaskType())){
                    //4.2 获取审核任务状态 任务状态，取值： WAITING：等待中； PROCESSING：处理中； FINISH：已完成； ABORTED：已终止。
                    String status = resp.getStatus();
                    if("FINISH".equals(status)){
                        //4.3 获取音视频审核任务结果
                        ReviewAudioVideoTask reviewAudioVideoTask = resp.getReviewAudioVideoTask();
                        if("FINISH".equals(reviewAudioVideoTask.getStatus())){
                            ReviewAudioVideoTaskOutput output = reviewAudioVideoTask.getOutput();
                            //音视频内容审核的结果建议，取值范围： pass：建议通过； review：建议复审； block：建议封禁。
                            String suggestion = output.getSuggestion();
                            log.info("音视频审核结果：{}", suggestion);
                            return suggestion.toLowerCase();
                        }
                    }
                }
            }
        } catch (TencentCloudSDKException e) {
            log.error("获取音视频审核结果失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return null;
    }
}

